<?php
namespace app\admin\controller;
use app\Base;
use think\facade\Db;
class Login extends Base{
	//private $request;
	
    public function index()
    {
		$post=array('username'=>$this->request->post('username'),'password'=>$this->request->post('password'));
		$msg=$this->validate($post,\app\admin\validate\User::class);
		if($msg)
		{
			return $this->kerror($msg);
		}		
		$password=skey($post['password']);
		
		$admin=Db::name('admin')->where('username',$post['username'])->find();
		if(!$admin['username'])
		{
			return $this->kerror('账号不存在');
		}
		if($admin['password']!=$password)
		{
			return $this->kerror('密码错误');
		}
		
		$role=Db::name('role')->where("roleid",$admin['roleid'])->find();
		$biaoshi=$role['roleid']?$role['biaoshi']:'user';
		$token=admintoken($admin['userid'],$admin['username']);
		$data=array('biaoshi'=>$biaoshi,'username'=>$admin['username'],'token'=>$token);
		$this->setobj($data);
		
		$this->inittoken($admin['userid'],$data);
		return $this->ok();
    }
	
	

    private function inittoken($userid,$data)
	{
		$info=array('inputtime'=>time(),'type'=>1,'expire'=>time()+3600*24*7,'token'=>$data['token'],'userid'=>$userid);
		Db::name('login_log')->insert($info);
		
	}
	
	
	
	public function geqqx()
	{
		$token=$this->request->post('token');
		if(!$token)
		{
			return $this->kerror('参数非法');
		}		
		
		$t=time();
		$tdata=Db::name('login_log')->where('token',$token)->where('expire','>',$t)->find();
		if($tdata['token'])
		{
			$admin=Db::name('admin')->where("userid",$tdata['userid'])->find();
			$biaoshi=Db::name('role')->where("roleid",$admin['roleid'])->value('biaoshi');
			$data=array('biaoshi'=>$biaoshi,'username'=>$admin['username'],'token'=>$token);
			$this->setobj($data);			
			return $this->ok();
		}
		return $this->kerror('token已过期');
	}
	
}
